package org.rency.crawler.dal.dao.impl;

import com.mongodb.client.result.DeleteResult;
import java.util.List;
import javax.annotation.Resource;
import org.rency.crawler.dal.dao.FetchStateDao;
import org.rency.crawler.dal.entity.FetchStateDO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/11/21 18:48<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/21 18:48
 */
@Repository
public class FetchStateDaoImpl implements FetchStateDao {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override
  public FetchStateDO load(String id) {
    Criteria criteria = Criteria.where("id").is(id);
    return mongoTemplate.findOne(new Query(criteria),FetchStateDO.class);
  }

  @Override
  public List<FetchStateDO> findAll() {
    return mongoTemplate.findAll(FetchStateDO.class);
  }

  @Override
  public FetchStateDO find(String fsCode) {
    Criteria criteria = Criteria.where("fsCode").is(fsCode);
    return mongoTemplate.findOne(new Query(criteria),FetchStateDO.class);
  }

  @Override
  public boolean save(FetchStateDO entity) {
    try {
      mongoTemplate.save(entity);
      return true;
    } catch (DuplicateKeyException e) {
      return true;
    }
  }

  @Override
  public boolean delete(String id) {
    DeleteResult result = mongoTemplate
        .remove(new Query(Criteria.where("id").is(id)), FetchStateDO.class);
    return result.getDeletedCount() == 1;
  }
}
